package com.zlsy.secondtime.background;

import java.util.Objects;

/**
 * @author zhouliang
 * @date 2020/5/19 14:58
 * 对象逸出之- 在构造函数中未初始化完毕就this赋值
 */
public class MultiThreadsError4 {

    static Point point;

    public static void main(String[] args) throws InterruptedException {
        PointMark pointMark = new PointMark();
        pointMark.start();
        Thread.sleep(1);

        if (Objects.nonNull(point)) {
            System.out.println(point.toString());
        }
    }
}

class Point {
    private final int x, y;

    public Point(int x, int y) throws InterruptedException {
        this.x = x;
        //把当前对象赋值给MultiThreadsError4对象的静态变量
        MultiThreadsError4.point = this;
        //问题就出在这里，y都还没赋值，就把当前对象赋值给某个类的静态变量了，导致这个类里面的属性可能随着初始化时间的不一致而产生不一致！
        Thread.sleep(10);
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

class PointMark extends Thread {
    @Override
    public void run() {
        try {
            new Point(1, 1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
